<?php

/**
 * User BaiXiantao
 * Date 2022/7/4
 * Time 14:00
 */

namespace app\admin\controller;

use app\admin\controller\Bot as ControllerBot;
use app\admin\model\Bot as ModelBot;
use app\admin\model\BotGroupmember;
use app\admin\model\BotMember;
use app\common\model\EmojiCode;
use app\common\model\kefu\Speechcraft;
use app\common\model\kefu\ChatLog;
use app\common\model\kefu\Config;
use app\constants\Bot;
use ky\Logger;
use think\facade\Log;

class Kefu extends Base
{
    private $emoji;
    private $configM;
    private $botM;
    private $emojiM;
    /**
     * @var ChatLog
     */
    private $chatLogM;

    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->emoji = new \ky\Emoji();
        $this->configM = new Config();
        $this->botM = new ModelBot();
        $this->emojiM = new EmojiCode();
        $this->chatLogM = new ChatLog();
    }


    public function index()
    {
        $base_config = $this->configM->getConf(['admin_id' => $this->adminInfo['id'], 'bot_id' => 0]);
        if (empty($base_config) || !isset($base_config['socket_ip']) || !isset($base_config['socket_port'])) {
            $this->error('请先设置应用配置');
        }
        $this->assign('from_id', $this->adminInfo['id']);
        $this->assign('socket_ip', $base_config['socket_ip']);
        $this->assign('socket_port', $base_config['socket_port']);

        return $this->show();
    }
    /**
     * 
     * 客服配置
     */
    public function config()
    {
        if (!$base_config = $this->configM->getConf(['admin_id' => $this->adminInfo['id'], 'bot_id' => 0])) {
            $base_config = [
                'switch' => 1,
                'socket_ip' => '',
                'socket_port' => 9506
            ];
        }
        $builder = new FormBuilder();
        $builder->setPostUrl(url('saveConfigPost'))
            ->addFormItem('basic_legend', 'legend', '基础配置', '基础配置')
            ->addFormItem('id', 'hidden', 'id', 'id')
            ->addFormItem('switch', 'radio', '是否开启', '是否开启', [1 => '是', 0 => '否'])
            ->addFormItem('socket_ip', 'text', 'Socket主机', 'Socket主机地址', [], 'required')
            ->addFormItem('socket_port', 'text', '端口号', 'Socket端口号', [], 'required')
            ->addFormItem('file_path', 'text', '微信文件地址', '微信文件地址如：D:\weixinjilu\WeChat Files', [], 'required')
            ->setFormData($base_config);
        return $builder->show();
    }

    public function saveConfigPost($jump_to = '/undefined', $data = [])
    {
        $jump_to = url('config');
        $post_data = $data ? $data : input('post.');
        unset($post_data['__token__']);
        foreach ($post_data as $k => $v) {
            if ($config = $this->configM->getOneByMap(['admin_id' => $this->adminInfo['id'], 'key' => $k, 'bot_id' => 0],  true, true)) {
                $this->configM->updateOne(['id' => $config['id'], 'value' => $v]);
            } else {
                $this->configM->addOne([
                    'admin_id' => $this->adminInfo['id'],
                    'bot_id' => 0,
                    'key' => $k,
                    'value' => $v
                ]);
            }
        }
        $this->success('数据保存成功', $jump_to);
    }


    public function test()
    {
        return $this->show();
    }

    public function getBot()
    {
        if (request()->isPost()) {
            $this->model = new ModelBot();
            $post_data = input('post.');
            $where = array_merge($this->staffWhere(), ['protocol' => ['<>', Bot::PROTOCOL_WEB], 'alive' => 1]);
            !empty($post_data['search_key']) && $where['nickname|title|uuid'] = ['like', '%' . $post_data['search_key'] . '%'];
            $total = $this->model->total($where, true);
            if ($total) {
                $list = $this->model->getList(
                    [$post_data['page'], $post_data['limit']],
                    $where,
                    ['alive' => 'desc'],
                    true,
                    true
                );
                foreach ($list as $k => $v) {
                    $auto_pass = $this->configM->getConf(['admin_id' => $this->adminInfo['id'], 'bot_id' => $v['id']], 'auto_pass', true);
                    $v['auto_pass'] = $auto_pass == '' ? false : $auto_pass;
                    $v['auto_reply'] = $this->configM->getConf(['admin_id' => $this->adminInfo['id'], 'bot_id' => $v['id']], 'auto_reply', true);
                    $v['new'] = 0;
                    $list[$k] = $v;
                }
            } else {
                $list = [];
            }
            $this->success('success', '', ['total' => $total, 'list' => $list]);
        }
    }

    /**
     * 
     * 获取客服好友
     */
    public function getFriends()
    {
        $this->model = new BotMember();
        $bot_model = new ModelBot();
        if (request()->isPost()) {
            $post_data = input('post.');
            $this->bot = $bot_model->getOne($post_data['id']);
            $where = [['type', 'in', [Bot::FRIEND, Bot::GROUP]], ['uin', '=', $this->bot['uin']]];
            !empty($post_data['search_key']) && $where[] = ['nickname|remark_name|username|wxid', 'like', '%' . $post_data['search_key'] . '%'];
            $total = $this->model->where($where)->count();
            if ($total) {
                $order = ['last_chat_time' => 'desc'];
                $list = $this->model->where($where)->page($post_data['page'])->limit($post_data['limit'])->order($order)->select()->toArray();
                // dump($this->model->getlastsql());exit;
                //  dump($this->model->getlastsql());exit;
                $redis = get_redis();
                $key = 'last_chat_log:' . $this->bot['uin'];
                $chat_log = $redis->hGetAll($key);
                foreach ($list as &$val) {
                    $hkey = $val['wxid'];
                    $last_chat_content = '';
                    if (isset($chat_log[$hkey])) {
                        $log = json_decode($chat_log[$hkey], true);
                        $last_chat_content = $log['content'];
                    }
                    $val['last_chat_content'] = $last_chat_content;
                    $val['new'] = 0;
                }
            } else {
                $list = [];
            }

            $this->success('success', '', ['total' => $total, 'list' => $list]);
        }
    }

    /**
     * 
     * 发送消息
     */
    public function sendMsg($post_data = [])
    {
        if (request()->isPost()) {
            if (!$post_data) {
                $post_data = input('post.');
            }
            $bot_model = new ModelBot();
            $chat_model = new ChatLog();
            $member_model = new BotMember();
            $date = date("Y-m-d H:i:s");
            $year = date("Y");
            $time = time();
            $bot = $bot_model->getOne($post_data['bot_id']);
            $content = $post_data['content'];
            // $content = $chat_model->convertMsg($content, $post_data['type']);
            // $last_chat_content = $content;
            // $bot_client = $bot_model->getRobotClient($bot);
            if ($post_data['type'] == 1) { //文本
                // $bot_client->sendTextToFriends([
                //     'robot_wxid' => $bot['uin'],
                //     'to_wxid' => $post_data['to_wxid'],
                //     'msg' => $post_data['content']
                // ]);
                $content = $this->emojiM->emojiText($post_data['content']);
                $last_chat_content = $content;
            } else if ($post_data['type'] == 3) { //图片
                // $bot_client->sendImgToFriends([
                //     'robot_wxid' => $bot['uin'],
                //     'to_wxid' => $post_data['to_wxid'],
                //     'path' => $post_data['content']
                // ]);
                $last_chat_content = '[图片]';
            } else if ($post_data['type'] == 2004) { //文件
                // $bot_client->sendFileToFriends([
                //     'robot_wxid' => $bot['uin'],
                //     'to_wxid' => $post_data['to_wxid'],
                //     'path' => $post_data['content']
                // ]);
                $last_chat_content = '[文件]';
            } else if ($post_data['type'] == 43) { //视频
                $last_chat_content = '[视频]';
            } else {
                $content = '[链接]';
                $last_chat_content = '[链接]';
            }
            $msgid = 'send_' . time() . $this->adminInfo['id'];
            // $insert_data = [
            //     'from' => $bot['uin'],
            //     'to' => $post_data['to_wxid'],
            //     'create_time' => $time,
            //     'content' => $post_data['content'],
            //     'year' => $year,
            //     'from_headimg' => $bot['headimgurl'],
            //     'msg_id' => $msgid,
            //     'type' => 'send',
            //     'msg_type' => $post_data['type'] //文本
            // ];
            // $chat_model->partition('p' . $year)->insertGetId($insert_data);
            //更改好友最后聊天时间
            if (isset($post_data['friend_id']) && $post_data['friend_id'] > 0) {
                $friend_id = $post_data['friend_id'];
            } else {
                $friend_id = $member_model->where(['uin' => $bot['uin'], 'wxid' => $post_data['to_wxid']])->order(['id' => 'desc'])->value('id');
            }
            $member_model->where(['id' => $friend_id])->update(['last_chat_time' => $time]);
            $friend = $member_model->where(['id' => $friend_id])->find();
            $friend['last_chat_content'] = $last_chat_content;

            $result = [
                'msg_id' => $msgid,
                'date' => $date,
                'content' => $content,
                'type' => 'send',
                'class' => 'my_chat_content',
                'quote' => $post_data['quote'] ?? '',
                'headimgurl' => $bot['headimgurl'],
                'friend' => $friend,
                'msg_type' => $post_data['type'],
            ];
            //最后一条聊天记录放redis
            $redis = get_redis();
            $key = 'last_chat_log:' . $bot['uin'];
            $hkey = $post_data['to_wxid'];
            $h_data = $result;
            $h_data['content'] = $last_chat_content;
            $redis->hSet($key, $hkey, json_encode($h_data));
            $this->success('success', '', $result);
        }
    }

    public function sendMsgPost($post_data = [])
    {
        if (request()->isPost()) {
            if (!$post_data) {
                $post_data = input('post.');
            }
            $bot_model = new ModelBot();
            $bot = $bot_model->getOne($post_data['bot_id']);
            $bot_client = $bot_model->getRobotClient($bot);
            if ($post_data['type'] == 1) { //文本
                $res = $bot_client->sendTextToFriends([
                    'robot_wxid' => $bot['uin'],
                    'to_wxid' => $post_data['to_wxid'],
                    'msg' => $post_data['content']
                ]);
            } else if ($post_data['type'] == 3) { //图片
                $res = $bot_client->sendImgToFriends([
                    'robot_wxid' => $bot['uin'],
                    'to_wxid' => $post_data['to_wxid'],
                    'path' => $post_data['content']
                ]);
            } else if ($post_data['type'] == 2004) { //文件
                // $res = $bot_client->sendFileToFriends([
                //     'robot_wxid' => $bot['uin'],
                //     'to_wxid' => $post_data['to_wxid'],
                //     'path' => $post_data['content']['url']
                // ]);
                $base_config = $this->configM->getConf(['admin_id' => $this->adminInfo['id'], 'bot_id' => 0]);
                $date = date("Y-m");
                $file_name = time().$post_data['content']['file_name'];
                $file_path = $base_config['file_path'] ?? "D:\weixinjilu\WeChat Files\WeChat Files";
                $savePath = $file_path."\\".$bot['uin']."\FileStorage\File\\".$date."\\".$file_name;
                $res = $bot_client->downloadAndSend([
                    'url' => $post_data['content']['url'],
                    'savePath' => $savePath,
                    'useApi' => 'SendFileMsg',
                    'robot_wxid' => $bot['uin'],
                    'to_wxid' => $post_data['to_wxid'],
                    
                ]);

            } else if ($post_data['type'] == 43) { //视频
                $res = $bot_client->sendVideoMsg([
                    'robot_wxid' => $bot['uin'],
                    'to_wxid' => $post_data['to_wxid'],
                    'path' => $post_data['content']
                ]);
            }
            $this->success('success', '', $res);
        }
    }

    /**
     * 
     * 添加话术
     */
    public function addSpeechcraft()
    {
        $input = input();
        if (!isset($input['bot_id'])) {
            $this->error('请选择客服');
        }
        $id = $input['bot_id'];
        $data = ['bot_id' => $id];
        $builder = new FormBuilder();
        $builder->setMetaTitle('新增话术')
            ->setPostUrl(url('saveSpeechcraft'))
            ->addFormItem('bot_id', 'hidden', 'ID', 'ID')
            ->addFormItem('title', 'text', '标题', '标题', [], 'required')
            ->addFormItem('content', 'textarea', '话术', '内容', [], 'required')
            ->setFormData($data)
            ->setBtnSubmit(0)
            ->setBtnReset(0);
        return $builder->show();
    }

    /**
     * 
     * 保存话术
     */
    public function saveSpeechcraft()
    {
        $post_data = input('post.');
        $this->model = new Speechcraft();
        unset($post_data['__token__']);
        if (empty($post_data['id'])) {
            $post_data['created_by'] = $this->adminInfo['id'];
            $res = $this->model->addOne($post_data);
        } else {
            $res = $this->model->updateOne($post_data);
        }

        if ($res) {
            $this->success('数据保存成功');
        } else {
            $this->error('数据保存出错');
        }
    }

    /**
     * 
     * 获取话术列表
     */
    public function getSpeechcraft()
    {
        if (request()->isPost()) {
            $this->model = new Speechcraft();
            $post_data = input('post.');
            $where = ['bot_id' => $post_data['bot_id'], 'status' => 1];
            // !empty($post_data['search_key']) && $where['nickname|title|uuid'] = ['like', '%' . $post_data['search_key'] . '%'];
            $total = $this->model->total($where, true);
            if ($total) {
                $list = $this->model->getList(
                    [$post_data['page'], $post_data['limit']],
                    $where,
                    ['id' => 'desc'],
                    true,
                    true
                );
            } else {
                $list = [];
            }
            $this->success('success', '', ['total' => $total, 'list' => $list]);
        }
    }


    /**
     * 
     * 修改好友备注
     */
    public function saveRemark()
    {
        $post_data = input('post.');
        $this->model = new BotMember();
        $bot_model = new ModelBot();
        $bot = $bot_model->getOne($post_data['bot_id']);
        $bot_client = $bot_model->getRobotClient($bot);
        $bot_client->setFriendRemarkName(['to_wxid' => $post_data['to_wxid'], 'note' => $post_data['remark_name']]);
        $res = $this->model->updateOne(['id' => $post_data['id'], 'remark_name' => $post_data['remark_name']]);
        $this->success('数据保存成功');
    }

    /**
     * 
     * 保存自动回复
     */
    public function saveAutoReply()
    {
        $post_data = input('post.');
        unset($post_data['__token__']);
        foreach ($post_data as $k => $v) {
            if ($config = $this->configM->getOneByMap(['admin_id' => $this->adminInfo['id'], 'key' => $k, 'bot_id' => $post_data['id']],  true, true)) {
                $this->configM->updateOne(['id' => $config['id'], 'value' => $v]);
            } else {
                $this->configM->addOne([
                    'admin_id' => $this->adminInfo['id'],
                    'bot_id' => $post_data['id'],
                    'key' => $k,
                    'value' => $v
                ]);
            }
        }
        $this->success('数据保存成功');
    }

    /**
     * 
     * 收藏消息
     */
    public function favoritesMsg()
    {
        if (request()->isPost()) {
            $post_data = input('post.');
            $bot_model = new ModelBot();
            $bot = $bot_model->where(['uin' => $post_data['robot_wxid']])->find();
            $bot_client = $bot_model->getRobotClient($bot);
            $params = [
                'robot_wxid' => $post_data['robot_wxid'],
                'msgid' => $post_data['msg_id'],
            ];
            $res = $bot_client->favoritesMsg($params);
            $this->success('收藏成功');
        }
    }

    /**
     * 
     * 获取好友聊天记录
     */
    public function getChatLog()
    {
        if (request()->isPost()) {
            $post_data = input('post.');
            $year = date("Y");
            $chat_model = new ChatLog();
            $member_model = new BotMember();
            $where = [['from|to', '=', $post_data['uin']], ['from|to', '=', $post_data['friend_wxid']]];
            $from_date = strtotime(date("Y-m-d"));
            $to_date = time();
            // $where[] = ['create_time', 'between', [$from_date, $to_date]];
            $order = ['create_time' => 'desc'];
            $limit = $post_data['limit'] ?? 30;
            $page = $post_data['page'] ?? 1;
            $total = $chat_model->partition('p' . $year)->where($where)->count();
            $log_list = [];
            if ($total) {
                $log_list = $chat_model->partition('p' . $year)->where($where)->order($order)->page($page)->limit($limit)->select();
                $friend = $member_model->where(['uin' => $post_data['uin'], 'wxid' => $post_data['friend_wxid']])->find();
                foreach ($log_list as &$val) {
                    $val['date'] = $val['create_time'];
                    $val['class'] = $val['type'] == 'send' ? 'my_chat_content' : 'friend_chat_content';
                    $val['headimgurl'] = $val['from_headimg'];
                    $val['friend'] = $friend;
                    $val['time'] = strtotime($val['create_time']);
                    $content = $chat_model->convertMsgToHtml($val['content'], $val['msg_type']);
                    $val['content'] = $content;
                }
            }

            // $result = [
            //     'msg_id' => $msgid,
            //     'date' => $date,
            //     'content' => $post_data['content'],
            //     'type' => 'send',
            //     'class' => 'my_chat_content',
            //     'quote' => $post_data['quote']??'',
            //     'headimgurl' => $bot['headimgurl'],
            //     'friend' => $friend,
            //     'msg_type' => $post_data['type'],
            // ];
            $this->success('success', '', ['list' => $log_list, 'total' => $total]);
        }
    }

    /**
     * 
     * 机器人登录
     */
    public function loginBot()
    {
        $ControllerBot = new ControllerBot;
        $data = array_merge([
            'protocol' => Bot::PROTOCOL_MY,
            'app_key' => get_rand_char(32),
            'jump' => '/admin/kefu'
        ], $ControllerBot->getConfig());

        cache('botadd' . $this->adminInfo['id'], $data);
        $this->redirect(url('/admin/Bot/loginmy', $data));
        // $this->success('请打开微信扫码登录', url('/admin/Bot/loginmy', $data));
    }

    /**
     * 
     * emoji转换
     */
    public function emojiConvert()
    {
        if (request()->isPost()) {
            $post_data = input('post.');
            $content = $this->emojiM->emojiText($post_data['content'], $post_data['to']);
            $this->success('success', '', ['content' => $content]);
        }
    }

    /**
     * 
     * 检查转账是否已同意
     */
    public function checkTransferMsg()
    {
        if (request()->isPost()) {
            $post_data = input('post.');
            $msg_id = $post_data['msg_id'];
            $is_read = $this->chatLogM->where(['msg_id' => $msg_id, 'type' => 'receive'])->value('is_read');
            if ($is_read != 0) {
                $this->error('转账已操作');
            } else {
                $this->success('ok');
            }
        }
    }


    /**
     * 
     * 同意转账
     */
    public function accepteTransfer()
    {
        if (request()->isPost()) {
            $post_data = input('post.');
            $msg_id = $post_data['msg_id'];
            $this->chatLogM->where(['msg_id' => $msg_id, 'type' => 'receive'])->update(['is_read' => 1]);
            $bot_model = $this->botM;
            $bot = $bot_model->getOne($post_data['bot_id']);
            $bot_client = $bot_model->getRobotClient($bot);
            $res = $bot_client->acceptTransfer([
                'robot_wxid' => $bot['uin'],
                'from_wxid' => $post_data['from_wxid'],
                'payer_pay_id' => $post_data['content']['payer_pay_id'],
                'receiver_pay_id' => $post_data['content']['receiver_pay_id'],
                'paysubtype' => $post_data['content']['paysubtype'],
                'money' => $post_data['content']['money'],
            ]);
            $this->success('success', '', $res);
        }
    }

    /**
     * 
     * 拒绝转账
     */
    public function rejectTransfer()
    {
        if (request()->isPost()) {
            $post_data = input('post.');
            $msg_id = $post_data['msg_id'];
            $this->chatLogM->where(['msg_id' => $msg_id, 'type' => 'receive'])->update(['is_read' => -1]);
            $bot_model = $this->botM;
            $bot = $bot_model->getOne($post_data['bot_id']);
            $bot_client = $bot_model->getRobotClient($bot);
            $res = $bot_client->rejectTransfer([
                'robot_wxid' => $bot['uin'],
                'receiver_pay_id' => $post_data['content']['receiver_pay_id'],
            ]);
            $this->success('success', '', $res);
        }
    }

    /**
     * 
     * 判断是否是好友
     */
    public function checkFirend()
    {
        if (request()->isPost()) {
            $post_data = input('post.');
            $member_model = new BotMember();
            $is_friend = 0;
            $friend = [];
            if ($friend = $member_model->where(['uin' => $post_data['bot_uin'], 'wxid' => $post_data['wxid']])->find()) {
                $is_friend = 1;
                $redis = get_redis();
                $key = 'last_chat_log:' . $post_data['bot_uin'];
                $chat_log = $redis->hGetAll($key);
                $hkey = $post_data['wxid'];
                $last_chat_content = '';
                if (isset($chat_log[$hkey])) {
                    $log = json_decode($chat_log[$hkey], true);
                    $last_chat_content = $log['content'];
                }
                $friend['last_chat_content'] = $last_chat_content;
            }
            $this->success('success', '', ['is_friend' => $is_friend, 'friend' => $friend]);
        }
    }

    /**
     * 
     * 更新好友聊天时间为最新
     */
    public function updateChatTime()
    {
        if (request()->isPost()) {
            $post_data = input('post.');
            $member_model = new BotMember();
            $time = time();
            $member_model->where(['uin' => $post_data['uin'], 'wxid' => $post_data['wxid']])->update(['last_chat_time' => $time]);
            $this->success('success', '', ['time' => $time]);
        }
    }
    /**
     * 
     * 添加好友
     */
    public function addFriend()
    {
        if (request()->isPost()) {
            $post_data = input('post.');
            $bot_model = $this->botM;
            $bot = $bot_model->getOne($post_data['bot_id']);
            $bot_client = $bot_model->getRobotClient($bot);
            // $account = $bot_client->searchAccount([
            //     'robot_wxid' => $post_data['uin'],
            //     'content' => $post_data['wxid']
            // ]);
            $res = $bot_client->addFriendBySearch([
                'robot_wxid' => $post_data['uin'],
                'v1' => $post_data['wxid'],
                'v2' => $post_data['wxid'],
                'msg' => $post_data['msg'],
                'scene' => Bot::SCENE_CARD,
                'type' => 1
            ]);
            Log::write('添加好友:---------' . json_encode($res));
            if ($res['Code'] != 0) {
                $this->error(json_encode($res));
                Log::write('添加好友错误:---------' . json_encode($res));
            } else {
                $this->success('success');
            }
        }
    }

    /**
     * 
     * 获取群成员
     */
    public function groupMember()
    {
        $this->model = new BotGroupmember();
        $post_data = input();
        $where = [['group_id', '=', $post_data['group_id']]];
        !empty($post_data['uin']) && $where[] = ['wxid', '<>', $post_data['uin']];
        $list = $this->model->where($where)->select()->toArray();
        $this->assign('list', $list);
        return $this->show();
    }


    /**
     * 
     * 发送消息并@
     */
    public function sendMsgAndAt($post_data = [])
    {
        if (request()->isPost()) {
            if (!$post_data) {
                $post_data = input('post.');
            }
            $bot_model = new ModelBot();
            $chat_model = new ChatLog();
            $member_model = new BotMember();
            $date = date("Y-m-d H:i:s");
            $year = date("Y");
            $time = time();
            $bot = $bot_model->getOne($post_data['bot_id']);
            $content = $post_data['content'] . $post_data['at_nickname'];
            // $content = $chat_model->convertMsg($content, $post_data['type']);
            // $last_chat_content = $content;
            // $bot_client = $bot_model->getRobotClient($bot);
            if ($post_data['type'] == 1) { //文本
                // $bot_client->sendTextToFriends([
                //     'robot_wxid' => $bot['uin'],
                //     'to_wxid' => $post_data['to_wxid'],
                //     'msg' => $post_data['content']
                // ]);
                $content = $this->emojiM->emojiText($content);
                $last_chat_content = $content;
            } else if ($post_data['type'] == 3) { //图片
                // $bot_client->sendImgToFriends([
                //     'robot_wxid' => $bot['uin'],
                //     'to_wxid' => $post_data['to_wxid'],
                //     'path' => $post_data['content']
                // ]);
                $last_chat_content = '[图片]';
            } else if ($post_data['type'] == 2004) { //文件
                // $bot_client->sendFileToFriends([
                //     'robot_wxid' => $bot['uin'],
                //     'to_wxid' => $post_data['to_wxid'],
                //     'path' => $post_data['content']
                // ]);
                $last_chat_content = '[文件]';
            } else if ($post_data['type'] == 43) { //视频
                $last_chat_content = '[视频]';
            } else {
                $content = '[链接]';
                $last_chat_content = '[链接]';
            }
            $msgid = 'send_' . time() . $this->adminInfo['id'];
            // $insert_data = [
            //     'from' => $bot['uin'],
            //     'to' => $post_data['to_wxid'],
            //     'create_time' => $time,
            //     'content' => $post_data['content'],
            //     'year' => $year,
            //     'from_headimg' => $bot['headimgurl'],
            //     'msg_id' => $msgid,
            //     'type' => 'send',
            //     'msg_type' => $post_data['type'] //文本
            // ];
            // $chat_model->partition('p' . $year)->insertGetId($insert_data);
            //更改好友最后聊天时间
            if (isset($post_data['friend_id']) && $post_data['friend_id'] > 0) {
                $friend_id = $post_data['friend_id'];
            } else {
                $friend_id = $member_model->where(['uin' => $bot['uin'], 'wxid' => $post_data['to_wxid']])->order(['id' => 'desc'])->value('id');
            }
            $member_model->where(['id' => $friend_id])->update(['last_chat_time' => $time]);
            $friend = $member_model->where(['id' => $friend_id])->find();
            $friend['last_chat_content'] = $last_chat_content;

            $result = [
                'msg_id' => $msgid,
                'date' => $date,
                'content' => $content,
                'type' => 'send',
                'class' => 'my_chat_content',
                'quote' => $post_data['quote'] ?? '',
                'headimgurl' => $bot['headimgurl'],
                'friend' => $friend,
                'msg_type' => $post_data['type'],
            ];
            //最后一条聊天记录放redis
            $redis = get_redis();
            $key = 'last_chat_log:' . $bot['uin'];
            $hkey = $post_data['to_wxid'];
            $h_data = $result;
            $h_data['content'] = $last_chat_content;
            $redis->hSet($key, $hkey, json_encode($result));
            $this->success('success', '', $result);
        }
    }

    public function sendMsgAndAtPost($post_data = [])
    {
        if (request()->isPost()) {
            if (!$post_data) {
                $post_data = input('post.');
            }
            $bot_model = new ModelBot();
            $bot = $bot_model->getOne($post_data['bot_id']);
            $bot_client = $bot_model->getRobotClient($bot);
            if ($post_data['type'] == 1) { //文本
                $bot_client->sendGroupMsgAndAt([
                    'robot_wxid' => $bot['uin'],
                    'group_wxid' => $post_data['to_wxid'],
                    'member_wxid' => $post_data['member_wxid'],
                    'msg' => $post_data['content']
                ]);
            } else if ($post_data['type'] == 3) { //图片
                $bot_client->sendImgToFriends([
                    'robot_wxid' => $bot['uin'],
                    'to_wxid' => $post_data['to_wxid'],
                    'path' => $post_data['content']
                ]);
            } else if ($post_data['type'] == 2004) { //文件
                $res = $bot_client->sendFileToFriends([
                    'robot_wxid' => $bot['uin'],
                    'to_wxid' => $post_data['to_wxid'],
                    'path' => $post_data['content']['url']
                ]);
            } else if ($post_data['type'] == 43) { //视频
                $bot_client->sendVideoMsg([
                    'robot_wxid' => $bot['uin'],
                    'to_wxid' => $post_data['to_wxid'],
                    'path' => $post_data['content']
                ]);
            }
            $this->success('success');
        }
    }


    /**
     * 
     * 发送消息并@所有人
     */
    public function sendMsgAndAtAll($post_data = [])
    {
        if (request()->isPost()) {
            if (!$post_data) {
                $post_data = input('post.');
            }
            $bot_model = new ModelBot();
            $chat_model = new ChatLog();
            $member_model = new BotMember();
            $date = date("Y-m-d H:i:s");
            $year = date("Y");
            $time = time();
            $bot = $bot_model->getOne($post_data['bot_id']);
            $content = $post_data['content'] . '@所有人';
            // $content = $chat_model->convertMsg($content, $post_data['type']);
            // $last_chat_content = $content;
            // $bot_client = $bot_model->getRobotClient($bot);
            if ($post_data['type'] == 1) { //文本
                // $bot_client->sendTextToFriends([
                //     'robot_wxid' => $bot['uin'],
                //     'to_wxid' => $post_data['to_wxid'],
                //     'msg' => $post_data['content']
                // ]);
                $content = $this->emojiM->emojiText($content);
                $last_chat_content = $content;
            } else if ($post_data['type'] == 3) { //图片
                // $bot_client->sendImgToFriends([
                //     'robot_wxid' => $bot['uin'],
                //     'to_wxid' => $post_data['to_wxid'],
                //     'path' => $post_data['content']
                // ]);
                $last_chat_content = '[图片]';
            } else if ($post_data['type'] == 2004) { //文件
                // $bot_client->sendFileToFriends([
                //     'robot_wxid' => $bot['uin'],
                //     'to_wxid' => $post_data['to_wxid'],
                //     'path' => $post_data['content']
                // ]);
                $last_chat_content = '[文件]';
            } else if ($post_data['type'] == 43) { //视频
                $last_chat_content = '[视频]';
            } else {
                $content = '[链接]';
                $last_chat_content = '[链接]';
            }
            $msgid = 'send_' . time() . $this->adminInfo['id'];
            // $insert_data = [
            //     'from' => $bot['uin'],
            //     'to' => $post_data['to_wxid'],
            //     'create_time' => $time,
            //     'content' => $post_data['content'],
            //     'year' => $year,
            //     'from_headimg' => $bot['headimgurl'],
            //     'msg_id' => $msgid,
            //     'type' => 'send',
            //     'msg_type' => $post_data['type'] //文本
            // ];
            // $chat_model->partition('p' . $year)->insertGetId($insert_data);
            //更改好友最后聊天时间
            if (isset($post_data['friend_id']) && $post_data['friend_id'] > 0) {
                $friend_id = $post_data['friend_id'];
            } else {
                $friend_id = $member_model->where(['uin' => $bot['uin'], 'wxid' => $post_data['to_wxid']])->order(['id' => 'desc'])->value('id');
            }
            $member_model->where(['id' => $friend_id])->update(['last_chat_time' => $time]);
            $friend = $member_model->where(['id' => $friend_id])->find();
            $friend['last_chat_content'] = $last_chat_content;

            $result = [
                'msg_id' => $msgid,
                'date' => $date,
                'content' => $content,
                'type' => 'send',
                'class' => 'my_chat_content',
                'quote' => $post_data['quote'] ?? '',
                'headimgurl' => $bot['headimgurl'],
                'friend' => $friend,
                'msg_type' => $post_data['type'],
            ];
            //最后一条聊天记录放redis
            $redis = get_redis();
            $key = 'last_chat_log:' . $bot['uin'];
            $hkey = $post_data['to_wxid'];
            $h_data = $result;
            $h_data['content'] = $last_chat_content;
            $redis->hSet($key, $hkey, json_encode($result));
            $this->success('success', '', $result);
        }
    }

    /**
     * 
     * 发送消息并@所有人
     */
    public function sendMsgAndAtAllPost($post_data = [])
    {
        if (request()->isPost()) {
            if (!$post_data) {
                $post_data = input('post.');
            }
            $bot_model = new ModelBot();
            $bot = $bot_model->getOne($post_data['bot_id']);
            $bot_client = $bot_model->getRobotClient($bot);
            if ($post_data['type'] == 1) { //文本
                $res = $bot_client->sendMsgAtAll(['robot_wxid' => $bot['uin'], 'group_wxid' => $post_data['to_wxid'], 'msg' => $post_data['content']]);
            } else if ($post_data['type'] == 3) { //图片
                $bot_client->sendImgToFriends([
                    'robot_wxid' => $bot['uin'],
                    'to_wxid' => $post_data['to_wxid'],
                    'path' => $post_data['content']
                ]);
            } else if ($post_data['type'] == 2004) { //文件
                $res = $bot_client->sendFileToFriends([
                    'robot_wxid' => $bot['uin'],
                    'to_wxid' => $post_data['to_wxid'],
                    'path' => $post_data['content']['url']
                ]);
            } else if ($post_data['type'] == 43) { //视频
                $res = $bot_client->sendVideoMsg([
                    'robot_wxid' => $bot['uin'],
                    'to_wxid' => $post_data['to_wxid'],
                    'path' => $post_data['content']
                ]);
            }
            $this->success('success', '', $res);
        }
    }


    /**
     * 
     * wxid获取群成员信息
     */
    public function getGroupMemberInfo()
    {
        if (request()->isPost()) {
            $post_data = input('post.');
            $bot_model = new ModelBot();
            $bot = $bot_model->getOne($post_data['bot_id']);
            $bot_client = $bot_model->getRobotClient($bot);
            $res = $bot_client->getGroupMemberInfo([
                'robot_wxid' => $bot['uin'],
                'group_wxid' => $post_data['group_wxid'],
                'member_wxid' => $post_data['member_wxid'],
            ]);

            if ($res['Code'] == 0 && isset($res['ReturnJson'])) {
                $info = $res['ReturnJson'];
                // backgroundimgurl: ""
                // city: "Xiamen"
                // country: "Xiamen"
                // group_name: "微信多客服测试优化"
                // group_wxid: "34907960925@chatroom"
                // headimgurl: "http://wx.qlogo.cn/mmhead/ver_1/rFBKIR8SsRnRPR18ftyqtToqyZxeYLqsRrg2o2z597cF1r69rRZHWEpRe1Nic2ukfpRzztENwP8cb0x2sichrshzojPXXmFLibuiasBibY5ge09c/0"
                // nickname: "DJ"
                // province: "Fujian"
                // scene: 0
                // sex: 1
                // signature: ""
                // wx_num: "doogiefu"
                // wxid: "wxid_xokb2ezu1p6t21"
                $this->success('success', '', $info);
            } else {
                $this->error('获取群成员信息错误');
            }
        }
    }

    /**
     * 
     * wxid获取好友信息
     */
    public function getDetailInfoByWxid()
    {
        if (request()->isPost()) {
            $post_data = input('post.');
            $bot_model = new ModelBot();
            $bot = $bot_model->getOne($post_data['bot_id']);
            $bot_client = $bot_model->getRobotClient($bot);
            $res = $bot_client->getDetailInfoByWxid([
                'robot_wxid' => $bot['uin'],
                'to_wxid' => $post_data['to_wxid'],
            ]);

            if ($res['Code'] == 0 && isset($res['ReturnJson'])) {
                $info = $res['ReturnJson'];
                // backgroundimgurl: ""
                // city: "Xiamen"
                // country: "Xiamen"
                // group_name: "微信多客服测试优化"
                // group_wxid: "34907960925@chatroom"
                // headimgurl: "http://wx.qlogo.cn/mmhead/ver_1/rFBKIR8SsRnRPR18ftyqtToqyZxeYLqsRrg2o2z597cF1r69rRZHWEpRe1Nic2ukfpRzztENwP8cb0x2sichrshzojPXXmFLibuiasBibY5ge09c/0"
                // nickname: "DJ"
                // province: "Fujian"
                // scene: 0
                // sex: 1
                // signature: ""
                // wx_num: "doogiefu"
                // wxid: "wxid_xokb2ezu1p6t21"
                $this->success('success', '', $info);
            } else {
                $this->error('获取群成员信息错误');
            }
        }
    }


    /**
     * 
     * 开启/关闭消息免打扰设置
     */
    public function updateMemberDnd()
    {
        if (request()->isPost()) {
            $post_data = input('post.');
            $this->model = new BotMember();
            $member = $this->model->where(['id' => $post_data['id']])->find();
            $this->model->where(['id' => $post_data['id']])->update(['dnd' => $post_data['dnd']]);
            $bot_model = new ModelBot();
            $bot = $bot_model->getOne($post_data['bot_id']);
            $bot_client = $bot_model->getRobotClient($bot);
            if ($post_data['dnd']) { //开启
                $res = $bot_client->onNotDisturb([
                    'robot_wxid' => $bot['uin'],
                    'content' => $member['wxid'],
                ]);
            } else {
                $res = $bot_client->offNotDisturb([
                    'robot_wxid' => $bot['uin'],
                    'content' => $member['wxid'],
                ]);
            }
            $this->success('success', '', $res);
        }
    }
}
